using MediatR;
using Medical.Api.Read.Application.Command.BasicManagement.EquipmentPackageDictionaryCommand;
using Medical.Domain.BasicManagement;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;

namespace Medical.Api.Read.Application.Handler.BasicManagement.EquipmentPackageDictionaryHandler
{
    /// <summary>
    /// 查询器械包列表处理器
    /// </summary>
    public class QueryEquipmentPackageHandler : IRequestHandler<QueryEquipmentPackageCommand, ApiResult<ApiPageIng<EquipmentPackage>>>
    {
        private readonly IBaseRepository<EquipmentPackage> _packageRepository;
        private readonly ILogger<QueryEquipmentPackageHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="packageRepository">器械包仓储</param>
        /// <param name="logger">日志记录器</param>
        public QueryEquipmentPackageHandler(
            IBaseRepository<EquipmentPackage> packageRepository,
            ILogger<QueryEquipmentPackageHandler> logger)
        {
            _packageRepository = packageRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理查询器械包列表请求
        /// </summary>
        /// <param name="request">查询命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页器械包列表</returns>
        public Task<ApiResult<ApiPageIng<EquipmentPackage>>> Handle(QueryEquipmentPackageCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询器械包列表");

                // 构建查询条件
                var query = _packageRepository.GetAll().Where(x => !x.IsDeleted);

                // 按类型筛选（如果提供）
                if (request.QueryDto.PackageType.HasValue)
                {
                    query = query.Where(x => x.PackageType == request.QueryDto.PackageType.Value);
                }

                // 按编码筛选（如果提供）
                if (!string.IsNullOrWhiteSpace(request.QueryDto.PackageCode))
                {
                    query = query.Where(x => x.PackageCode.Contains(request.QueryDto.PackageCode));
                }

                // 按名称筛选（如果提供）
                if (!string.IsNullOrWhiteSpace(request.QueryDto.PackageName))
                {
                    query = query.Where(x => x.PackageName.Contains(request.QueryDto.PackageName));
                }

                // 按状态筛选（如果提供）
                if (request.QueryDto.Status.HasValue)
                {
                    query = query.Where(x => x.Status == request.QueryDto.Status.Value);
                }

                // 计算总记录数
                int total = query.Count();

                // 分页查询
                var pagedData = query
                    .OrderByDescending(x => x.CreateTime) // 按创建时间降序排序
                    .Skip((request.QueryDto.PageIndex - 1) * request.QueryDto.PageSize)
                    .Take(request.QueryDto.PageSize)
                    .ToList();

                // 构建分页结果
                var pageResult = new ApiPageIng<EquipmentPackage>
                {
                    TotalCount = total,
                    PageData = pagedData
                };

                _logger.LogInformation("成功查询器械包列表，总记录数：{TotalCount}", total);

                return Task.FromResult(new ApiResult<ApiPageIng<EquipmentPackage>>
                {
                    Code = ApiEnums.Success,
                    Msg = "查询成功",
                    Data = pageResult
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询器械包列表时发生异常");
                return Task.FromResult(new ApiResult<ApiPageIng<EquipmentPackage>>
                {
                    Code = ApiEnums.Fail,
                    Msg = "查询失败：系统内部错误",
                    Data = new ApiPageIng<EquipmentPackage>()
                });
            }
        }
    }
}